package mvc.mainPage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import utils.UsersOnlineHttpSessionAttributeListener;

import domain.Message;
import domain.Room;
import domain.User;

import DAO.IMessageDAO;
import DAO.IRoomDAO;
import DAO.IUserDAO;

import mvc.IController;
import mvc.IModel;

@Component
public class MainController implements IController {

	private static Logger log = Logger.getLogger(MainController.class);
	
	@Autowired
	private IMessageDAO messageDao;
	
	@Autowired
	private IRoomDAO roomDao;
	
	@Autowired
	private IUserDAO userDao;
	
	@Override
	public IModel execute(IModel model) {
		
		MainModel mainModel = (MainModel) model;
		//BL 
		
		mainModel.setRooms( getActiveRooms() );
		mainModel.setMessages( getFormattedMessages(mainModel) );
		mainModel.setUsersOnline( getUsersOnline(mainModel) );
		
		if (mainModel.getUserLogin()!=null && mainModel.getUserLogin().isEmpty())
		{
			mainModel.setErrorMessage("Login empty!");
		}else if (mainModel.getUserPassword()!=null && mainModel.getUserPassword().isEmpty())
		{
			mainModel.setErrorMessage("Password Empty!");
		}
		
		return mainModel;
				
	}

	private List<String> getUsersOnline(MainModel mainModel) {
		
		List<String> chatUsers = new ArrayList<String>();
			
		Map<Integer, Integer> usersOnline = UsersOnlineHttpSessionAttributeListener.getActiveUsers();
		Integer currentRoomId = mainModel.getCurrentRoomId();
		for (Integer user_id : usersOnline.keySet()) {
			
			if ( currentRoomId.equals( usersOnline.get(user_id) ) ) {
				
				User user = userDao.getUser( user_id );
				if (user != null) chatUsers.add( user.getUserNickName() );
			}			
		}
		
		log.debug("getUsersOnline : " + Arrays.toString(chatUsers.toArray()) );
		return chatUsers;
	}

	private List<String> getFormattedMessages(MainModel mainModel) {
		
		List<String> messages = new ArrayList<String>();
		
		if ( mainModel.getCurrentRoomId() != null) {
			Room room = roomDao.SelectRoom( mainModel.getCurrentRoomId() );
			
			for (Message msgObj : room.getMessages()) {
				String message = String.format("[%1s] %2s : %3s", msgObj.getCreateDate(), msgObj.getUser().getUserNickName(), msgObj.getMsg());
				messages.add( message );	
			}
			
		} 
			
		log.debug("getMessages : " + Arrays.toString(messages.toArray()) );
				
		return messages;
	}

	private List<Room> getActiveRooms() {
		
		List<Room> activeRooms = roomDao.SelectRooms();
		
		log.debug("getActiveRooms : " + Arrays.toString(activeRooms.toArray()) );		
		return activeRooms;
	}
	
	

}
